package com.cloud.form.api.web;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.form.api.entity.FormValue;
import com.cloud.form.api.service.FormValueService;
import com.cloud.form.common.result.Quokka;
import com.cloud.form.common.utils.MediaStorageHelper;
import com.cloud.form.common.utils.UUIDHelper;
import com.cloud.form.common.utils.WordHelper;

@RestController
@RequestMapping("/form/api/value")
public class FormValueController {

	@Autowired
	private FormValueService formValueService;

	/**
	 * 保存或更新文书值
	 * 
	 * @param value
	 * @return
	 */
	@RequestMapping("saveupdatevalue")
	public Quokka saveUpdateFormValue(FormValue value) {
		// TODO:调用写数据源，更新业务库
		formValueService.saveUpdateFormValue(value);
		return new Quokka(true);
	}

	/**
	 * 获取已填写文书详情
	 * 
	 * @param value
	 * @return
	 */
	@RequestMapping("loadvalue")
	public Quokka loadValue(@RequestBody FormValue value) {
		FormValue result = formValueService.loadFormValue(value);
		if (null != result) {
			return new Quokka(true, result);
		} else {
			// TODO: 调用读数据源，填写默认值
			result = new FormValue();
			return new Quokka(true, result);
		}
	}

	/**
	 * 文书图片上传
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("image/upload")
	public Quokka imageUpload(MultipartFile file) throws Exception {
		String filepath = new StringBuilder("form/image/").append(UUIDHelper.generateUUID().toUpperCase())
				.append(".jpg").toString();
		MediaStorageHelper.upload(file.getInputStream(), filepath);
		return new Quokka(true, filepath);
	}

	/**
	 * 文书打印预览
	 * 
	 * @param value
	 * @return
	 */
	@RequestMapping("printview")
	public Quokka printView(@RequestBody FormValue value) {
		byte[] wordContent = formValueService.printView(value);
		Map<String, String> result = new HashMap<String, String>();
		result.put("wordContent", Base64.getEncoder().encodeToString(wordContent));
		result.put("pdfContent", Base64.getEncoder().encodeToString(WordHelper.word2Pdf(wordContent)));
		return new Quokka(true, result);
	}

}
